export default EquilateralPolygon
import {c, mouse} from "./canvas";

// n为边数
// x y为中心坐标
// a为中心到顶点的距离
// ang为逆时针旋转角度， 默认为0
function EquilateralPolygon(n, x, y, a, ang = 0, color = 'white') {
    this.n = n;
    this.x = x;
    this.y = y;
    this.a = a;
    this.ang = ang - Math.PI * 0.5;
    this.color = color;
    this.points = [];
    this.makePoints = function () {
        let tempAng = this.ang;
        const rotateAng = 2 * Math.PI / n;
        for (let i = 0; i < this.n; ++i) {
            this.points[i] = [this.a * Math.cos(tempAng), this.a * Math.sin(tempAng)];
            tempAng = tempAng - rotateAng;
        }
    }

    this.show = function () {
        // c.beginPath();
        // let tempAng = this.ang;
        // const rotateAng = 2 * Math.PI / n;
        // c.moveTo(this.x + this.a * Math.cos(tempAng), this.y + this.a * Math.sin(tempAng));
        // for (let i = 0; i < this.n; ++i) {
        //     tempAng = tempAng - rotateAng;
        //     c.lineTo(this.x + this.a * Math.cos(tempAng), this.y + this.a * Math.sin(tempAng));
        // }
        // c.fillStyle = this.color;
        // c.fill();
        // c.closePath();
        // c.stroke();
        c.beginPath();

        for (let i = 0; i < this.n; ++i) {
            c.lineTo(this.x + this.points[i][0], this.y + this.points[i][1]);
        }
        c.fillStyle = this.color;
        c.fill();
        c.closePath();
        c.stroke();
    }

    // 一个静态的多边形
    this.update = function () {
        this.makePoints();
        this.show();
    }

    // 一个跟随鼠标转动的多边形
    this.updateWithMouse = function () {
        if (mouse.x === this.x) this.ang = -Math.PI * 0.5;
        else this.ang = Math.atan((mouse.y - this.y) / (mouse.x - this.x));
        this.show();
    }

    // 一个随机转动的多边形
    this.updateWithRandomAngle = function () {
        this.ang = this.ang + Math.random() % 2 * Math.PI;
        this.show();
    }

    this.changeAngle = function (ang) {
        this.ang = ang - Math.PI * 0.5;
    }

    this.changePosition = function (x, y) {
        this.x = x;
        this.y = y;
    }
}
